package com.mobile.dao;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.PersistentClass;


public class HibernateSessionFactory {

    /** 
     * LOGGER						为log4j对象
     * CONFIG_FILE_LOCATION			文件地址第一次调用此类是加载
     * threadLocal					为一个session线程
     * configuration				为配置文件对象
     * configFile					放置加载配置文件的参数
     */
	private static final Logger LOGGER = LogManager.getLogger(HibernateSessionFactory.class);
    private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    
	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			LOGGER.error("创建configure出错", e);
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    public HibernateSessionFactory() {
    }
	
	/**
	 * 获得一个session的线程
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  通过configFile参数重新设置SessionFactory通过configFile参数
     *
     */
	public static void rebuildSessionFactory() {
		try {
			/*if(configuration==null){
				configuration=new Configuration();
			}*/
			configuration=new Configuration();
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}
	/**
	 * 关闭SessionFactory
	 *
	 */
	public static void closeFactory(){
		try{
			sessionFactory.close();
		}
		catch(Exception e)
		{
			LOGGER.error("关闭SessionFactory出错", e);
			e.printStackTrace();
		}
	}
	/**
     * 关闭一个session线程
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.clear();
        	session.close();
        }
    }
    
	/**
     *  返回sessionFactory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  返回sessionFactory
     *
     *	下次加载此类是加载configFile的配置文件
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}
	/**
	 * 得到事务处理
	 * @return    Transaction
	 */
	public static Transaction getTransation()
	{
		Transaction transaction=null;
		try {
			transaction = HibernateSessionFactory.getSession()
					.beginTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			LOGGER.error("创建Transaction出错", e);
			e.printStackTrace();
		}		
		
		return transaction;
	}
	/**
	 * 提交事务
	 * @param transaction 要提交的事务
	 * @param commit 判断是否提交事务，读取操作时不需要事务提交，设置为false可以提高效率
	 */
	public static void endTransaction(Transaction transaction,boolean commit)
	{
		if(commit)
		{
			try {
				transaction.commit();
			} catch (Exception e) {
				// TODO: handle exception
				LOGGER.error("事务提交出错", e);
				e.printStackTrace();
			}			
		}
		else
		{
			transaction.rollback();
		}
	}
	/**
	 * 事务回滚
	 *
	 */
	public static void rollback(Transaction transaction)
	{
		if(transaction!=null)
		{
			try{
				transaction.rollback();
			}
			catch(Exception e)
			{
				LOGGER.error("事务回滚出错", e);
				e.printStackTrace();
			}
		}
	}
	/**
	 * 获取映射中的实体类
	 * @param entityName		实体名称
	 * @return
	 */
	public static PersistentClass getClassMapping(String entityName){
		return getConfiguration().getClassMapping(entityName);
	}
	
	public static  void reset(){
		Session session=getSession();
		if(session!=null){
			session.flush();
			if(session.isOpen()){
				System.out.println("closing session...");
				session.clear();
				System.out.println("ok");
			}
		}
		SessionFactory sf=getSessionFactory();
		if(sf!=null){
			LOGGER.info("closeing session factory...");
			sf.close();
			LOGGER.info("ok");
		}
		configuration=null;
		sessionFactory=null;
		session=null;
		threadLocal.set(session);
	}
}